<template>
  <div class="article-list" @scroll="rememberLocation" ref="articellist">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <article-item @click.native="gotoDetail(item.art_id)" v-for="item in articleList" :key="item.art_id" :article="item"/>
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import articleItem from './articleItem.vue'
import { getChannelArticle } from '@/api/channel.js'
export default {
  props: ['cid'],
  async created () {
    // //  获取该频道下的 文章列表
    // const [err, data] = await getChannelArticle(this.cid, this.pre_timestamp)
    // if (err) this.$toast.fail(err.message)
    // console.log(data)
    // // 1.将pre_timestamp 赋值
    // this.pre_timestamp = data.data.pre_timestamp
    // // 2.将列表赋值
    // this.articleList = data.data.results
  },
  data () {
    return {
      articleList: [],
      pre_timestamp: +new Date(),
      refreshing: false,
      loading: false,
      finished: false,
      scrollTop: 0
    }
  },
  deactivated () {
    // 记忆当前的位置

  },
  activated () {
    this.$refs.articellist.scrollTop = this.scrollTop
  },
  methods: {
    gotoDetail (aid) {
      this.$router.push('/article?id=' + aid)
    },
    rememberLocation () {
      this.scrollTop = this.$refs.articellist.scrollTop
    },
    async onLoad () {
      // 1.请求数据
      const [err, data] = await getChannelArticle(this.cid, this.pre_timestamp)
      if (err) this.$toast.fail(err.message)
      //   2.将数据加入到artilcel
      this.articleList.push(...data.data.results)
      //   3. 时间戳更新
      if (data.data.pre_timestamp) {
        this.pre_timestamp = data.data.pre_timestamp
      } else {
        this.finished = true
      }

      this.loading = false
    },
    async onRefresh () {
      // 1.设置时间戳
      this.pre_timestamp = +new Date()
      // 2.请求数据
      const [err, data] = await getChannelArticle(this.cid, this.pre_timestamp)
      if (err) this.$toast.fail(err.message)
      // 3.将pre_timestamp 赋值
      this.pre_timestamp = data.data.pre_timestamp
      // 4.将列表赋值
      this.articleList = data.data.results

      //   5.加载完成
      this.refreshing = false
    }
  },
  components: {
    articleItem
  }
}
</script>
<style scoped lang="less">
.article-list {
  height: 100%;
  overflow-y: auto;
  padding: 0 16px;
}
</style>
